package com.bjy.qa.agent.tools.script;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.bjy.qa.agent.response.Response;
import groovy.lang.Binding;
import groovy.lang.GroovyShell;

import java.util.HashMap;
import java.util.Map;

/**
 * Groovy 脚本
 */
public class GroovyScript implements Script {

    @Override
    public Response run(Response response, Map<String, Object> globalParas, String script) {
        // 执行脚本
        Binding binding = new Binding();
        binding.setVariable("response", response);
        binding.setVariable("globalParas", globalParas);
        GroovyShell gs = new GroovyShell(binding);
        Object result = gs.evaluate(script);

        // 生成返回结果
        Map<String, Object> ret = new HashMap<>();
        ret.put("ret", result);
        String resultJson = JSON.toJSONString(ret, new SerializerFeature[]{SerializerFeature.WriteMapNullValue});
        Response responseReturn = new Response(resultJson, null);

        return responseReturn;
    }

}
